package com.springboot.framework.service.impl;

import com.springboot.framework.dao.entity.User;
import com.springboot.framework.dao.mapper.UserMapper;
import com.springboot.framework.enums.StatusEnum;
import com.springboot.framework.exception.BusinessException;
import com.springboot.framework.model.BuyerModel;
import com.springboot.framework.model.SellerModel;
import com.springboot.framework.service.BuyerService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;

/**
 * @Author SWF
 * @Date 2019/6/10 16:26
 **/
@Service
public class BuyerServiceImpl implements BuyerService {

    @Resource
    private UserMapper userMapper;

    /**
     * openID登录
     *
     * @param openId
     * @return
     */
    @Override
    public BuyerModel loginByOpenId(String openId) {
        BuyerModel buyerModel = getByOpenId(openId);
        if(buyerModel == null){
           buyerModel = new BuyerModel();
           buyerModel.setWechatOpenid(openId);
           buyerModel = insert(buyerModel);
        }
        return buyerModel;
    }

    @Override
    public BuyerModel getByOpenId(String openId){
        Example example = new Example(User.class);
        example.and().andEqualTo("wechatOpenid",openId)
                .andNotEqualTo("status", StatusEnum.DELETE.getCode());
        User user = userMapper.selectOneByExample(example);
        return convertBuyerModelFromBuyer(user);
    }

    @Override
    public BuyerModel insert(BuyerModel buyerModel) {
        User user = convertUser(buyerModel);
        userMapper.insertSelective(user);
        return convertBuyerModelFromBuyer(user);
    }

    private User convertUser(BuyerModel buyerModel){
        User user = new User();
        BeanUtils.copyProperties(buyerModel,user);
        return user;
    }

    private BuyerModel convertBuyerModelFromBuyer(User user){
        if(user == null){
            return null;
        }
        BuyerModel buyerModel = new BuyerModel();
        BeanUtils.copyProperties(user,buyerModel);
        buyerModel.setUserType(StatusEnum.NORMAL_USER.getCode());
        return buyerModel;
    }
}
